﻿using MeterReader.WPF.Models;
using Microsoft.Xaml.Behaviors;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace MeterReader.WPF.Behaviors
{
    public class FilterMeterStatusBehavior : Behavior<RadioButton>
    {
        public CollectionViewSource FilterSource
        {
            get { return (CollectionViewSource)GetValue(FilterSourceProperty); }
            set { SetValue(FilterSourceProperty, value); }
        }

        public static readonly DependencyProperty FilterSourceProperty = DependencyProperty.Register(
            "FilterSource",
            typeof(CollectionViewSource),
            typeof(FilterMeterStatusBehavior),
            new PropertyMetadata()
        );

        public MeterStatus Target
        {
            get { return (MeterStatus)GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
        }

        public static readonly DependencyProperty TargetProperty = DependencyProperty.Register(
            "Target",
            typeof(MeterStatus),
            typeof(FilterMeterStatusBehavior),
            new PropertyMetadata()
        );

        protected override void OnAttached()
        {
            AssociatedObject.Click += OnClick;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.Click -= OnClick;
        }

        private void OnClick(object sender, RoutedEventArgs e)
        {
            switch (Target)
            {
                case MeterStatus.Working:
                    FilterMeterStatus(MeterStatus.Working);
                    break;

                case MeterStatus.Fault:
                    FilterMeterStatus(MeterStatus.Fault);
                    break;

                case MeterStatus.Default:
                    FilterMeterStatus(MeterStatus.Fault, MeterStatus.Working);
                    break;

                default:
                    FilterMeterStatus(MeterStatus.Fault, MeterStatus.Working);
                    break;
            }
        }

        private void FilterMeterStatus(params MeterStatus[] meterStatuses)
        {
            if (FilterSource != null)
            {
                FilterSource.Filter += new FilterEventHandler(
                    (sender, e) =>
                    {
                        var collection = e.Item as MeterDataCollection;
                        if (collection != null)
                        {
                            e.Accepted = meterStatuses.Contains((MeterStatus)collection.MeterLatestData.MeterStatus!);
                        }
                        else
                        {
                            e.Accepted = false;
                        }
                    }
                );
            }
            FilterSource!.View.Refresh();
        }
    }
}